package com.jsyl.lwbk.business.handle;

import com.alibaba.fastjson.JSON;
import com.aliyun.oss.HttpMethod;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.GeneratePresignedUrlRequest;
import com.aliyun.oss.model.ObjectMetadata;
import com.jsyl.lwbk.business.dto.AliOssDTO;
import com.jsyl.lwbk.system.service.ISysConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Date;

/**
 * @author xiaoshu
 * @date 2020-12-26 16:06
 * @desc
 **/
@Component
public class AliOssHandle {

    @Autowired
    private ISysConfigService sysConfigService;

    public String upload(String filePath, File file, InputStream inputStream) {
        AliOssDTO ossDto = createAliOssDTO();
        OSSClient ossClient = new OSSClient(ossDto.getEndpoint(), ossDto.getAccessKeyId(), ossDto.getAccessKeySecret());
        ObjectMetadata meta = new ObjectMetadata();
        // 设置为访问返回url直接下载
        meta.setContentType("application/octet-stream");
        if (file != null) {
            ossClient.putObject(ossDto.getBucketName(), filePath, file, meta);
        } else if (inputStream != null) {
            ossClient.putObject(ossDto.getBucketName(), filePath, inputStream, meta);
        }
        String url;
        if (ossDto.getExpiration() != null && ossDto.getExpiration() != -1) {
            GeneratePresignedUrlRequest req = new GeneratePresignedUrlRequest(ossDto.getBucketName(), filePath, HttpMethod.GET);
            Date exp = new Date(new Date().getTime() + ossDto.getExpiration() * 1000);
            req.setExpiration(exp);
            url = ossClient.generatePresignedUrl(req).toString();
        } else {
            url = "http://" + ossDto.getBucketName() + "." + ossDto.getEndpoint() + "/" + filePath;
        }
        ossClient.shutdown();
        return url;
    }

    private AliOssDTO createAliOssDTO() {
        String config = sysConfigService.selectConfigByKey("business.ali.oss");
        AliOssDTO ossDto = JSON.parseObject(config, AliOssDTO.class);
        return ossDto;
    }

    private String encoder(String s) {
        try {
            String encoder = URLEncoder.encode(s, "UTF-8");
            encoder = encoder.replaceAll("\\+", "%20");
            encoder = encoder.replaceAll("\\*", "%2A");
            return encoder;
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return null;
    }

}
